package com.common.code.msgpack;

import com.common.message.vo.BaseMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.msgpack.MessagePack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class MsgPackDecode extends MessageToMessageDecoder<ByteBuf> {

    private final static Logger logger = LoggerFactory.getLogger(MsgPackDecode.class);
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        try {
            logger.info("enter decode start");
            final byte[] array;
            final int length = msg.readableBytes();
            array = new byte[length];
            msg.getBytes(msg.readerIndex(), array, 0, length);
            MessagePack msgpack = new MessagePack();
            out.add(msgpack.read(array, BaseMessage.class));
            logger.info("enter decode end");
        }catch(Exception e){
            logger.error("decode is exception: {}",e);
        }
    }

}
